/**
 * 随机数据生成工具
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
let id = 0;

/**
 * 生成id
 * @returns number
 */
export function nextId(): number {
  return ++id;
}

/**
 * 生成随机中文
 * @returns {string}
 */
function randomChinese(): string {
  let str = `\\u${randomNumber(19968, 40869).toString(16)}`;
  str = str.replace(/\\u/g, '%u');
  return unescape(str);
}

/**
 * 随机数值
 * @param min 最小值
 * @param max 最大值
 * @param decimalLen 小数点长度
 * @returns {number}
 */
export function randomNumber(min = -Infinity, max = Infinity, decimalLen = 0): number {
  if (min > max) {
    const t = min;
    min = max;
    max = t;
  }
  if (decimalLen > 0) {
    return Number((Math.random() * (max - min) + min).toFixed(decimalLen));
  }
  return Math.floor(Math.random() * (max - min)) + min;
}

/**
 * 随机布尔值
 */
export function randomBoolean() {
  return randomNumber(0, 1) === 1;
}

/**
 * 随机字符串
 * @param length 长度，范围长度：0,10，固定长度：10
 * @param source 源字符串（生成的字符串从这里面随机取）
 * @returns {string}
 */
export function randomString(length: string | number, source?: string): string {
  if (typeof source === 'string') {
    const srts: string[] = source.split('');
    // @ts-ignore
    source = () => {
      return srts[randomNumber(0, srts.length)];
    };
  } else {
    // @ts-ignore
    source = randomChinese;
  }
  if (typeof length === 'string') {
    // @ts-ignore
    length = length.split(',');
    // @ts-ignore
    if (length.length === 1) {
      length = Number(length);
      // @ts-ignore
      length = [length, length];
    } else {
      // @ts-ignore
      length = [Number(length[0]), Number(length[1])];
    }
  } else if (typeof length === 'number') {
    // @ts-ignore
    length = [length, length];
  } else {
    // @ts-ignore
    length = [4, 20];
  }
  // @ts-ignore
  length = randomNumber(length[0], length[1]);
  const list = [];
  for (let i = 0; i < length; i++) {
    // @ts-ignore
    list.push(source());
  }
  return list.join('');
}

/**
 * 生成随机代码
 * @param length 代码长的
 * @param source 源字符串
 * @returns {string}
 */
export function randomCode(
  length: string | number = '4,4',
  source = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
): string {
  return randomString(length, source);
}

/**
 * 生成随机数组
 * @param supplier 数组元素供应器
 * @param maxLength 数组最大长度，默认：100
 * @param minLength 数组最小长度，默认：0
 * @returns {*[]}
 */
export function randomArray(supplier: Function, maxLength = 100, minLength = 0): any[] {
  minLength = randomNumber(minLength, maxLength);
  const list: any = [];
  for (let i = 0; i < minLength; i++) {
    list.push(supplier(i));
  }
  return list;
}

/**
 * 获取随机元素
 * @param source 源数组
 * @param otherValue 用于模拟空值返回，不设置则都从数组里面取
 */
export function randomElement(source: any[], otherValue?: any): any {
  const index = randomNumber(otherValue === undefined ? 0 : -1, source.length);
  return index === -1 ? otherValue : source[index];
}
